<template>
  <!-- 简单的图片懒加载，实现是通过规定的可视区域的scrollTop+可视区域的高度
   跟 某一张图片的offsetTop比较 -->
  <div>
    <div class="box" ref="box">
      <img
        v-for="(item, index) in data"
        :key="index"
        src="../../assets/imgs/err.png"
        :data-img="item.img"
      />
    </div>
  </div>
</template>

<script lang="ts">
import {
  ref,
  reactive,
  watch,
  toRefs,
  computed,
  onMounted,
  onUpdated,
  onUnmounted,
} from "vue";
import { useLocalStorage } from "@vueuse/core";
export default {
  setup(_, context) {
    const data = ref([
      {
        img: "/src/assets/imgs/0.png",
      },
      {
        img: "/src/assets/imgs/0.png",
      },
      {
        img: "/src/assets/imgs/0.png",
      },
      {
        img: "/src/assets/imgs/0.png",
      },
      {
        img: "/src/assets/imgs/0.png",
      },
      {
        img: "/src/assets/imgs/0.png",
      },
    ]);
    const box = ref();
    const time = ref();
    onMounted(() => {
      box.value.addEventListener("scroll", fn());
    });
    onUnmounted(() => {
      box.value.removeEventListener("scroll");
    });

    // 节流
    const fn = () => {
      clearTimeout(time.value);
      return () => {
        time.value = setTimeout(() => {
          handle();
        }, 1000);
      };
    };

    // 处理函数
    const handle = () => {
      box.value.childNodes.forEach((value: HTMLElement) => {
        // 判断图片的距离顶部的高度和父元素滚动距离加上父元素高度
        if (value.offsetTop < box.value.clientHeight + box.value.scrollTop) {
          value.src = value.getAttribute("data-img");
        }
      });
    };
    return {
      box,
      data,
    };
  },
};
</script>

<style  scoped>
.box {
  margin: 0 auto;
  margin-top: 30px;

  width: 300px;
  height: 300px;
  background-color: wheat;
  overflow: auto;
  scroll-snap-type: y mandatory;
}
img {
  scroll-snap-align: center;
}
</style>